import 'package:blurb/common/values/svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:blurb/common/store/share_store.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:blurb/common/models/user.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:typed_data';
import 'package:blurb/common/values/images.dart';
import 'package:blurb/common/models/share.dart';
import 'package:blurb/common/services/share_service.dart';

// 扩展Share类，添加本地图片数据支持
class LocalImageShare extends Share {
  final Uint8List? imageData;

  LocalImageShare({
    required int id,
    required String description,
    required String picture,
    required String time,
    required int userId,
    this.imageData,
  }) : super(
          id: id,
          description: description,
          picture: picture,
          time: time,
          userId: userId,
        );
}

class SharingPublishPage extends StatefulWidget {
  // 静态变量，用于存储最近发布的图片数据
  static Map<int, List<Uint8List>> publishedImages = {};
  
  const SharingPublishPage({super.key});

  @override
  State<SharingPublishPage> createState() => _SharingPublishPageState();
}

class _SharingPublishPageState extends State<SharingPublishPage> {
  final TextEditingController _contentController = TextEditingController();
  List<AssetEntity> _selectedAssets = [];
  Map<String, Uint8List?> _selectedImagesData = {};
  User? _currentUser;
  bool _isLoading = false;
  
  // 草稿相关
  static const String _draftKey = 'share_draft';
  
  @override
  void initState() {
    super.initState();
    _getCurrentUser();
    _loadDraft();
  }
  
  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }
  
  // 获取当前登录用户
  Future<void> _getCurrentUser() async {
    final userStore = Provider.of<UserStore>(context, listen: false);
    setState(() {
      _currentUser = userStore.currentUser;
    });
  }
  
  // 加载草稿
  Future<void> _loadDraft() async {
    if (_currentUser == null) return;
    
    final prefs = await SharedPreferences.getInstance();
    final draftStr = prefs.getString('${_draftKey}_${_currentUser!.id}');
    
    if (draftStr != null) {
      final draftMap = jsonDecode(draftStr);
      
      setState(() {
        _contentController.text = draftMap['content'] ?? '';
        // 图片路径保存在草稿中，需要重新加载
        // 实际项目中可能需要更复杂的逻辑来恢复选中的图片
      });
    }
  }
  
  // 保存草稿
  Future<void> _saveDraft() async {
    if (_currentUser == null) return;
    
    final prefs = await SharedPreferences.getInstance();
    final draftMap = {
      'content': _contentController.text,
      // 保存图片路径等信息
      'timestamp': DateTime.now().toIso8601String(),
    };
    
    await prefs.setString('${_draftKey}_${_currentUser!.id}', jsonEncode(draftMap));
  }
  
  // 清除草稿
  Future<void> _clearDraft() async {
    if (_currentUser == null) return;
    
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('${_draftKey}_${_currentUser!.id}');
  }
  
  // 选择图片
  Future<void> _pickImages() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 2, // 最多选择2张图片
        selectedAssets: _selectedAssets,
        requestType: RequestType.image,
      ),
    );
    
    if (result != null) {
      setState(() {
        _selectedAssets = result;
      });
      
      // 加载图片数据
      for (var asset in result) {
        final Uint8List? data = await asset.thumbnailData;
        if (data != null) {
          setState(() {
            _selectedImagesData[asset.id] = data;
          });
        }
      }
    }
  }
  
  // 发布分享
  Future<void> _publishShare() async {
    if (_contentController.text.trim().isEmpty) {
      Fluttertoast.showToast(
        msg: "Please write something",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
      );
      return;
    }
    
    if (_selectedAssets.isEmpty) {
      Fluttertoast.showToast(
        msg: "Please select at least one image",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
      );
      return;
    }
    
    setState(() {
      _isLoading = true;
    });
    
    try {
      final shareStore = Provider.of<ShareStore>(context, listen: false);
      
      // 收集所有选择的图片数据
      List<Uint8List> imagesData = [];
      List<String> picturePaths = [];
      
      for (var asset in _selectedAssets) {
        final imageData = _selectedImagesData[asset.id];
        if (imageData != null) {
          imagesData.add(imageData);
          
          // 在实际项目中，这里应该上传图片并获取URL
          // 这里简化处理，使用预设图片路径
          final String picturePath = _selectedAssets.indexOf(asset) == 0 
              ? MIP.sunscreen1 
              : MIP.sunscreen2;
          picturePaths.add(picturePath);
        }
      }
      
      // 获取所有分享，确定新分享ID
      final allShares = await ShareService.getAllShares();
      final newShareId = allShares.isEmpty ? 1 : allShares.map((share) => share.id).reduce((a, b) => a > b ? a : b) + 1;
      
      // 使用第一张图片作为主图片
      final String mainPicture = picturePaths.isNotEmpty ? picturePaths[0] : MIP.sunscreen1;
      
      // 使用支持多张图片的公开方法添加分享
      final bool success = await shareStore.addShareWithPictures(
        _contentController.text,
        mainPicture,
        _currentUser!.id,
        pictures: picturePaths,
      );
      
      if (success && imagesData.isNotEmpty) {
        // 保存图片数据到静态变量，以便在分享列表中显示
        SharingPublishPage.publishedImages[newShareId] = imagesData;
        
        // 清除草稿
        await _clearDraft();
        
        // 返回上一页
        if (mounted) {
          GoRouter.of(context).pop();
        }
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }
  
  // 显示保存草稿对话框
  void _showSaveDraftDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF1F1F21),
        title: Text(
          'Save Draft',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        ),
        content: Text(
          'After saving the draft, the currently entered content will not be lost after exiting the page.',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.normal,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(
              'Cancel',
              style: GoogleFonts.racingSansOne(
                color: Colors.white70,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          GestureDetector(
            onTap: () async {
              await _saveDraft();
              if (mounted) {
                Navigator.of(context).pop();
                GoRouter.of(context).pop();
              }
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.96),
                  colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                ),
                borderRadius: BorderRadius.circular(30.r),
              ),
              child: Text(
                'Save',
                style: GoogleFonts.racingSansOne(
                  color: Colors.white,
                  fontSize: 18.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          'Release',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontWeight: FontWeight.normal,
            fontSize: 24.sp,
          ),
        ),
        centerTitle: true,
        actions: [
          TextButton(
            onPressed: _showSaveDraftDialog,
            child: Text(
              'Save Draft',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontWeight: FontWeight.normal,
                fontSize: 16.sp,
                decoration: TextDecoration.underline,
                decorationColor: Colors.white,
                decorationThickness: 1.w,
                decorationStyle: TextDecorationStyle.solid,
              ),
            ),
          ),
        ],
      ),
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(
                color: Color(0xFF60C3FF),
              ),
            )
          : Column(
              children: [
                SizedBox(height: 20.h),
                // 用户头像和提示文本
                Center(
                  child: Column(
                    children: [
                      Container(
                        width: 80.w,
                        height: 80.h,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          border: Border.all(color: Colors.white, width: 2.w),
                          image: DecorationImage(
                            image: _currentUser != null
                                ? AssetImage(_currentUser!.avatar)
                                : const AssetImage('assets/images/avatar.png'),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      SizedBox(height: 10.h),
                      Text(
                        _currentUser != null ? _currentUser!.nickname : 'Guest',
                        style: GoogleFonts.racingSansOne(
                          color: Colors.white,
                          fontSize: 18.sp,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(height: 5.h),
                      Text(
                        'Share your sun protection tips now',
                        style: GoogleFonts.inter(
                          color: Colors.white70,
                          fontSize: 14.sp,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 20.h),
                // 内容输入区域
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                      decoration: BoxDecoration(
                        color: const Color(0xFF1F1F21),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TextField(
                            controller: _contentController,
                            style: GoogleFonts.inter(
                              color: Colors.white,
                            ),
                            maxLines: 5,
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: 'Write Down Your Feelings',
                              hintStyle: GoogleFonts.inter(
                                color: Colors.grey,
                              ),
                              icon: Padding(
                                padding: EdgeInsets.only(top: 12.h),
                                child: Icon(MSI.edit, color: Colors.grey),
                              ),
                            ),
                          ),
                          SizedBox(height: 10.h),
                          Divider(
                            color: Colors.white.withOpacity(0.1),
                            height: 1.h,
                            thickness: 1.w,
                          ),
                          SizedBox(height: 10.h),
                          // 显示已选择的图片
                          if (_selectedAssets.isNotEmpty)
                            Wrap(
                              spacing: 8.w,
                              runSpacing: 8.h,
                              children: _selectedAssets.map((asset) {
                                final Uint8List? imageData = _selectedImagesData[asset.id];
                                
                                return Stack(
                                  children: [
                                    Container(
                                      width: 100.w,
                                      height: 100.h,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(8.r),
                                        image: imageData != null
                                            ? DecorationImage(
                                                image: MemoryImage(imageData),
                                                fit: BoxFit.cover,
                                              )
                                            : null,
                                        color: Colors.grey[800],
                                      ),
                                      child: imageData == null
                                          ? const Center(
                                              child: CircularProgressIndicator(),
                                            )
                                          : null,
                                    ),
                                    Positioned(
                                      right: 0,
                                      top: 0,
                                      child: GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            _selectedAssets.remove(asset);
                                            _selectedImagesData.remove(asset.id);
                                          });
                                        },
                                        child: Container(
                                          padding: EdgeInsets.all(4.w),
                                          decoration: const BoxDecoration(
                                            color: Colors.black54,
                                            shape: BoxShape.circle,
                                          ),
                                          child: Icon(
                                            Icons.close,
                                            color: Colors.white,
                                            size: 16.sp,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                );
                              }).toList(),
                            ),
                          const Spacer(),
                          // 添加图片按钮
                          GestureDetector(
                            onTap: _selectedAssets.length < 2 ? _pickImages : null,
                            child: Padding(
                              padding: EdgeInsets.only(bottom: 16.h),
                              child: Container(
                                width: 60.w,
                                height: 60.h,
                                decoration: BoxDecoration(
                                  color: _selectedAssets.length < 2 
                                      ? const Color(0xFF2A2A2A)
                                      : Colors.grey[800],
                                  borderRadius: BorderRadius.circular(12.r),
                                ),
                                child: Center(
                                  child: Icon(
                                    Icons.add,
                                    color: _selectedAssets.length < 2 
                                        ? Colors.white
                                        : Colors.grey,
                                    size: 30.sp,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                // 底部按钮
                Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Column(
                    children: [
                      GestureDetector(
                        onTap: _publishShare,
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                          width: double.infinity,
                          height: 56.h,
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              begin: Alignment(0.50, 0.00),
                              end: Alignment(0.50, 0.96),
                              colors: [
                                Color(0xFF60C3FF),
                                Color(0xFFAADEFC),
                              ],
                            ),
                            borderRadius: BorderRadius.circular(39.r),
                          ),
                          child: Center(
                            child: Text(
                              'Release',
                              style: GoogleFonts.racingSansOne(
                                color: Colors.white,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 4.h),
                      TextButton(
                        onPressed: () {
                          setState(() {
                            _contentController.clear();
                            _selectedAssets = [];
                            _selectedImagesData = {};
                          });
                        },
                        child: Center(
                          child: Text(
                            'Reset',
                            style: GoogleFonts.racingSansOne(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.normal,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 16.h),
                      Text(
                        'EULA',
                        style: GoogleFonts.inter(
                          color: Colors.white.withOpacity(0.8),
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w500,
                          decoration: TextDecoration.underline,
                          decorationColor: Colors.white.withOpacity(0.8),
                          decorationThickness: 1.w,
                          decorationStyle: TextDecorationStyle.solid,
                        ),
                      ),
                      SizedBox(height: 20.h),
                    ],
                  ),
                ),
              ],
            ),
    );
  }
} 